<?php
/*
* -default_sort [defind sort column] /array('by' => array('4','3'), 'order' => array('0'));
* -addon_class [add class for table] /class name
* -header_def [define header name] /array('s_id','name')
* -pattern [defind pattern for each column /array('<b>{id}</b>','<span>{name}</span>')
* -values [all data] /array(1 => array('id' => '1','name' => 'beem'),2 => array('id' => '2','name' => 'beem2'));
* -pager [use pagination] /1
*
* */
function fw_list_js($data){
	global $dd;
	if ($data['data_values'] && is_array($data['data_values'])) {
		//create row pattern for table
		$pattern = '';
		foreach ($data['pattern'] as $d => $inf) {
			$pattern .= '<td>'.$inf.'</td>';
		}
		$r .= '<table cellspacing="1" cellpadding="4" class="tablesorter '.$data['addon_class'].'" id="'.$data['table_id'].'">
		<thead>
		<tr>';
		//create headers for table
		foreach ($data['header_def'] as $k => $v) {
			$class = '';
			$css = '';
			if (substr($v,0,2) == 's_') {
				$hx = explode('_',$v,2);
				$headers = $hx[1];
				$class = ' {sorter: false}';
			} else {
				$headers = $v;
				$class = ' sortableColumn';
			}
			$r .= '<th class="fw-formListHead'.$class.'">' . $headers . '</th>';
		}
		$r .= '</tr>
			</thead>
		<tbody>
		';

		//change values in template
		foreach ($data['data_values'] as $k => $v) {
			$values = array_values($v);
			if (!isset($replace_pattern)) {
				$tmp = array_keys($v);
				foreach ($tmp as $kk => $vv) {
					$replace_pattern[$kk]= '{'.$vv.'}';
				}
			}
			$class_show = '';
			if ($data['row_class_add']) {
				if (array_key_exists($values[0],$data['row_class_add'])) {
					$class_show = ' class="'.$data['class_show'].'"';
				}
			}
			$r .= '<tr id_item="'.$values[0].'"'.$class_show.'>'.str_replace($replace_pattern, $values, $pattern).'</tr>';
		}
		//[0,0], [1,0]

		if ($data['pager'] == 1) $data['js_function'] = 'tablesorterPager({container: $("#pager_'.$data['table_id'].'")});';
		if (is_array($data['default_sort']['by'])) {
			foreach ($data['default_sort']['by'] as $i => $v) {
				$sort .= '['.$v.','.$data['default_sort']['order'][$i].'], ';
			}
			$sort = substr($sort, 0,-2);
		} else $sort = '['.$data['default_sort']['by'].','.$data['default_sort']['order'].']';
			if ($data['js_option'] != '') $data['js_option'] = ",\n".$data['js_option']; else $data['js_option'] = '';
			if ($data['js_function'] != '') $data['js_function'] = '.'.$data['js_function'].';'; else $data['js_function'] = ';';

			$r .= '</tbody>';
			if ($data['add_more_row']) $add_more_row = $data['add_more_row'];
			$r .= $add_more_row.'</table>

			<script type="text/javascript">
			$(document).ready(function(){
				$("table#'.$data['table_id'].'").tablesorter({
					widgets: ["zebra"],
					sortList: ['.$sort.']'.$data['js_option'].'//,
					//sortEnd: shownow()
				})'.$data['js_function'].'
			});
			</script>
			';
			if ($data['pager'] == 1) {
				$r .= '<div id="pager_'.$data['table_id'].'" class="pager" style="clear: both;">
						<form>
							<img src="im/first.png" class="first"/>
							<img src="im/prev.png" class="prev"/>
							<input type="text" class="pagedisplay"/>
							<img src="im/next.png" class="next"/>
							<img src="im/last.png" class="last"/>
							<select class="pagesize">
								<option selected="selected" value="10">10</option>
								<option value="20">20</option>
								<option value="30">30</option>
								<option value="40">40</option>
							</select>
						</form>
					</div><br/><br/>
				';
			}
		}else $r = '<div class="fw-list_empty">'.INF_LIST_EMPTY.'</div>';
	return $r;
}


/**
 * Enter description here...
 *
 * @param unknown_type $data
 * @param unknown_type $values
 * @return unknown
 */
function fw_list_create($data, $pattern_, $add_row='', $resizeable=''){
	global $dd, $ui_theme, $user_theme;
	//$head_line = '<br class="clr"/>';
	if ($data['disable_dynamic_grid'] != 1) {
		$more_options = '';
		if ($data['more_options']) {
			foreach ($data['more_options'] as $k => $v) {
				$more_options .= '<div class="right_bar" style="border-left: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';">'.$v.'</div>';
			}
		}
		if ($data['sortable'] == 1) {
			$sortable_button = '<div class="right_bar" style="border-left: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';"><a href="#'.msg('sortable').'" onclick="show_popup_link(this,\'ajax=1&mod=entities&view=sortable&entity='.$data['entity'].'\',1,300);"><span title="'.msg('reorder_list').'" style="position: relative; cursor: pointer; padding: 5px 5px 5px 20px; margin: 0pt 4px;"><span style="position: absolute; top: 3px; left: 1px;"><span class="ui-icon ui-icon-shuffle"></span></span> '.msg('reorder_list').'</span></a></div>';
		}
		if ($_REQUEST[$data['entity_key']]['limit']) {
			$default_limit = $_REQUEST[$data['entity_key']]['limit'];
		} else {
			$default_limit = $_SESSION[SESSION_A]['result_per_page'];
		}

		if ($data['manage_grid'] != 1) {
			if ($_REQUEST['view']) {
				$more_link = '&entity_mod='.$_REQUEST['mod'].'&item_id='.$_REQUEST['item_id'];
			} else {
				$more_link = '&entity_mod='.$data['entity'].'&item_id='.$_REQUEST['item_id'];
			}
			$resizeable_opt = '<div class="right_bar" style="border-left: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';"><a href="#'.msg('manage grid').'" onclick="show_popup_link(this,\'fajax=1&mod=entities&view=search_result_manage&entity='.$data['entity'].'&entity_key='.$data['entity_key'].$more_link.'\',1,1000);"><span title="'.msg('manage grid').'" style="position: relative; cursor: pointer; padding: 5px 0 5px 20px; margin: 0 6px 0 4px"><span style="position: absolute; top: 3px; left: 0px;"><span class="ui-icon ui-icon-gear"></span></span>'.msg('manage grid').'</span></a></div>';
		}

		$hide = ' class="hide"';

		if ($data['search_form'] != '-' && $data['search_form'] != '0') {
			$c_search_hide = '';
			$c_search_show = ' hide';
			if ($_SESSION[SESSION_A]['search_layout'] != 'S') {// || !$data['search']['hide_form']
				$c_search_hide = ' hide';
				$c_search_show = '';
			}
			
			$search_icon = '<div class="right_bar" style="border-left: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';"><a href="#'.msg('search').'" onclick="show_search_form_js(\''.$data['entity_key'].'\');"><span title="'.msg('search').'" style="position: relative; cursor: pointer; padding: 5px 5px 5px 20px; margin: 0pt 4px;"><span style="position: absolute; top: 3px; left: 1px;"><span class="ui-icon ui-icon-search"></span></span> <span class="' . $data['entity_key']. '_hide' . $c_search_hide . '">'.msg('hide search').'</span><span class="'.$data['entity_key'].'_show' . $c_search_show . '">'.msg('show search').'</span></span></a></div>';

			//TODO check permission
			if ($data['history_icon'] == 1) {
				$history_icon = '<div class="right_bar" style="border-left: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';"><a href="#'.msg('search history').'" onclick="show_popup_link(this,\'fajax=1&mod=search&view=history&entity='.$data['entity_key'].'\',0);"><span title="'.msg('search history').'" style="position: relative; cursor: pointer; padding: 5px 5px 5px 20px; margin: 0pt 4px;"><span style="position: absolute; top: 3px; left: 1px;"><span class="ui-icon ui-icon-clipboard"></span></span> '.msg('search history').'</span></a></div>';
			}
			$hide = '';
		}

		$refresh_icon = '<div class="right_bar" style="border-left: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';">
			<a href="#'.msg('search').'" onclick="load_page(\'#'.$data['refresh_action_ajax'].'\',\'index.php?ajax=1&mod='.$data['op'].$data['link'].'\')">
				<span title="'.msg('refresh').'" style="position: relative; cursor: pointer; padding: 5px 5px 5px 12px; margin: 0pt 4px;"><span style="position: absolute; top: 3px; left: 1px;"><span class="ui-icon ui-icon-refresh"></span>
			</a>
		</div>';

		//set perpage dropdown
		if ($data['data_values'] && !$data['perpage']) {
			$per_page = '<div'.$hide.' class="left_bar" style="border-right: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';">' . msg('show') . ' ' . form_select('limit', array('default' => $default_limit, 'param2' => 'N', 'values' => '1:5:10', 'req' => 1, 'addon_field' => ' onchange="entity_limit_per_page(this, \''.$data['entity_key'].'\');" style="margin-right: 5px; margin-left: 5px;"')). ' ' . msg('results').'</div>';
		}
	
		if ($data['pagination']) {
			$pagination = '<div class="left_bar" style="border-right: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';">'.$data['pagination'].'</div>';
		}

		if ($data['custom_bar']) {
			$custom_bar = $data['custom_bar'];
		}

		$head_line .= '<div style="padding: 4px 4px 0; border-top: 1px solid #E3E3E3; border-left: 1px solid #E3E3E3; border-right: 1px solid #E3E3E3;">
			<div class="ui-state-active table_bar" style="border: 0; margin-top: 5px;">'.$pagination.$per_page.$refresh_icon.$history_icon.$search_icon.$sortable_button.$resizeable_opt.$more_options.$custom_bar.'</div>
		</div>';
	}

	$style = '';
	if ($data['header_name']['table'] && !$resizeable) {
		$style .= ' width="'.$data['header_name']['table'].'"';
	}
	//set default for empty table to 100%
	if (!$data['data_values']) {
		$style = ' width="98%"';
	}

	$r .= $head_line;
	$r .= '<table cellspacing="1" cellpadding="4" id="table_listing_'.$data['entity_key'].'"'.$style.' class="fw-items_list ui-widget fw-table_effect">
	<thead>';
	if ($data['data_values']) {
		//create row pattern for table
		//$pattern_ = array_values($pattern_);
		$pattern_shorthand = $pattern_['shorthand'];
		unset($pattern_['shorthand']);
		
		$pattern = '';
		if ($_REQUEST['export'] != 1) {
			if ($pattern_['checkbox']) {
				$pattern .= '<td class="fw-center">'.$pattern_['checkbox'].'</td>';
			}
		}
		if ($pattern_) {
			foreach ($pattern_ as $d => $inf) {
				if ($d != 'options' && $d != 'checkbox') {
					$pattern .= '<td>'.$inf.'</td>';
				}
			}
		}
		//export area
		if ($_REQUEST['export'] != 1) {
			if ($pattern_['options']) {
				$pattern .= '<td>'.$pattern_['options'].'</td>';
			}
		}

		$r .= '
		<tr class="ui-state-default">';
		//create headers for table
		//$val1 = $data['header_name']['all'];
		if ($data['header_name']['name']['checkbox']) {
			$width = '';
			if (isset($data['header_name']['width']['checkbox'])) {
				$width = ' width="'.$data['header_name']['width']['checkbox'].'"';
			}
			$r .= '<th'.$width.' rel="checkbox">'.$data['header_name']['name']['checkbox'].'</th>';
			unset($data['header_name']['name']['checkbox']);
		}
		$h_export = '';
		$width_export = array();
		$j = -1;
		foreach ($data['header_name']['name'] as $k => $v) {
			++$j;
			if ($k != 'options' && $k != 'shorthand') {
				$width = '';
				if (isset($data['header_name']['width'][$k])) {
					if ($_REQUEST['export'] == 1) {
						$width_export[$j]['key'] = $k;
						$width_export[$j]['start'] = $j;
						$width_export[$j]['stop'] = $j;
						$w = (int)($data['header_name']['width'][$k]/8);
						if ($w < 9) {
							$w = 9;							
						}
						$width_export[$j]['width'] = $w;
					}
					$width = ' width="'.$data['header_name']['width'][$k].'"';
				} else {
					if ($_REQUEST['export'] == 1) {
						$width_export[$j]['key'] = $k;
						$width_export[$j]['start'] = $j;
						$width_export[$j]['stop'] = $j;
						$width_export[$j]['width'] = 30;
					}
				}
				// class="fw-form_list_head"
				$r .= '<th'.$width.' rel="'.$k.'">';
				//export area
				if ($_REQUEST['export'] == 1) {
					$h_export .= '<th>';
				}
				if (is_array($v)) {
					foreach ($v as $i => $o) {
						$r .= $o;
						//export area
						if ($_REQUEST['export'] == 1) {
							$h_export .= strip_tags($o);
						}
						if ($v[$i+1] != '') {
							$r .= '|';
							//export area
							if ($_REQUEST['export'] == 1) {
								$h_export .= '|';
							}
						}
					}
				} else {
					$r .= $v;
					//export area
					if ($_REQUEST['export'] == 1) {
						$h_export .= strip_tags($v);
					}
				}
				$r .= '</th>';
				//export area
				if ($_REQUEST['export'] == 1) {
					$h_export .= '</th>';
					++$h_export_cnt; 
				}
			}
		}
		if ($_REQUEST['export'] == 1) {
			$t_export[] = $h_export;
		}

		if ($data['header_name']['name']['options']) {
			$width = '';
			if (isset($data['header_name']['width']['options'])) {
				$width = ' width="'.$data['header_name']['width']['options'].'"';
			}
			$r .= '<th'.$width.' rel="options">'.$data['header_name']['name']['options'].'</th>';
		}

		$r .= '</tr>
			</thead>
		<tbody>
		';
		//change values in template
		foreach ($data['data_values'] as $k => $v) {
			$values = array_values($v);
			if (!isset($replace_pattern)) {
				$tmp = array_keys($v);
				foreach ($tmp as $kk => $vv) {
					$replace_pattern[$kk]= '{'.$vv.'}';
				}
			}
			//export area
			if ($_REQUEST['export'] == 1) {
				$values = export_clean($values);
				$replace_pattern = export_clean($replace_pattern);
				$t_export[] = str_replace($replace_pattern, export_clean($values), $pattern);
			} else {
				$class_show = '';
				$style_show = '';
				#set verify class on tr .fw_verify_items
				if ($data['verify'] == 1) {
					if ($v['verified'] == '') {
						$class_show = ' fw_verify_items';
					}
				}
				if ($v['tr_option']['class']) {
					$class_show .= ' ' . $v['tr_option']['class'];
				}
				if ($v['tr_option']['style']) {
					$style_show = ' style="' . htmlspecialchars($v['tr_option']['style']) . '"';
				}
				$r .= '<tr class="fw-event'.(++$l%2) . $class_show.'"'.$style_show.'>' . str_replace($replace_pattern, $values, $pattern) . '</tr>';
				$info .= str_replace($replace_pattern, $values, $pattern_shorthand);
			}
		}
		//export area
		if ($_REQUEST['export'] == 1) {
			$at .= '<table>';
			if ($t_export) {
				foreach ($t_export as $kt => $vt) {
					$at .= '<tr>'.$vt.'</tr>';
				}
			}
			$at .= '</table>';
			$table = array(
				$data['entity'] => array(
					'table' => $at,
					'header' => msg('report'),
					'column_width' => $width_export,
					'set_page' => array('setLandscape' => 1, 'setPaper' => 9),
				)
			);
			fw_export_excel($table, $data['entity']);
			exit;
		}

		if ($data['disable_dynamic_grid'] != 1) {
			//display result per page
			if ($data['entity_key']) {
				$entity_key = $data['entity_key'];
			} else {
				$entity_key = $data['entity'];
			}
			// style="float: left; line-height: 25px; padding-left: 5px;"
			$t .= '<div class="left_bar">
						<span id="'.$entity_key.'_selector">selected 1 out of 10</span>
					</div>
					<script type="text/javascript">
						var pattern_selector = "'.msg('pattern_selector').'";
						var pattern_selected_none = "'.msg('pattern_selected_none').'";
						search_checksum["'.$entity_key.'"] = ' . (int)$data['search']['search_checksum'] .';
						var count_items_selected = new Array();
						$(document).ready(function(){
							fw_selector_update(\''.$entity_key.'\');
						});
					</script>';
	
			if ($data['actions']) {
				ksort($data['actions']);
				$export_type = array('actions');
				//$action .= '<br />';
				foreach ($export_type as $k2 => $v2) {
					$t .= '
					<div id="'.$entity_key.'_selector_action" class="hide" style="border-right: 1px solid '.$ui_theme[$user_theme]['highlight_bd'].';"> 
						<a id="'.$v2.'_'.$entity_key.'" tabindex="0" href="#'.$v2.'" class="fg-button fg-button-icon-right ui-widget ui-state-default">
							<span class="ui-icon ui-icon-triangle-1-s"></span>'.msg($v2).'
						</a>
					</div>
					<div class="hidden" id="'.$entity_key.'_selector_content">
						<ul>
						';
						foreach ($data['actions'] as $k => $v) {
							$action = ' href="#'.$k.'"';
							if ($v['onclick'] != '') {
								$action = ' onClick="'.$v['onclick'].'"';
							} else if ($v['anchor']) {
								$action = ' href="'.$v['anchor'].'"';
							}
		
							$action = str_replace('{token}', '\''.$data['search']['search_token'].'\'', $action);
							$action = str_replace('{items_selected}', 'fw_get_item(this,\''.$entity_key.'\')', $action);
							$action = str_replace('{basics_linked}', $data['linked'], $action);
							$action = str_replace('{check_sum}', $data['search']['search_checksum'], $action);
							//sub actions
							$sub_action = '';
							if ($data['actions_sub'][$k]) {
								$sub_action .= '<ul>';
								foreach ($data['actions_sub'][$k] as $k2 => $v2) {
									$action_sub = ' href="#'.$k2.'"';
									if ($v2['onclick'] != '') {
										$action_sub = ' onClick="'.$v2['onclick'].'"';
									} else if ($v2['anchor']) {
										$action_sub = ' href="'.$v2['anchor'].'"';
									}
			
									$action_sub = str_replace('{token}', '\''.$data['search']['search_token'].'\'', $action_sub);
									$action_sub = str_replace('{items_selected}', 'fw_get_item(this,\''.$data['entity'].'\')', $action_sub);
									$action_sub = str_replace('{basics_linked}', $data['linked'], $action_sub);
									$sub_action .= '<li><a'.$action_sub.'>'.$v2['label'].'</a></li>';
								}
								$sub_action .= '</ul>';
							}
							$t .= '<li><a'.$action.'>'.$v['label'].'</a>'.$sub_action.'</li>';
						}
						$t .= '
						</ul>
					</div>';
				}
	
				$script = '
					//selected items
					notify_word["'.$data['entity_key'].'"] = " '.msg($data['entity']) .' '. msg('selected').'";
					for (x in item_selected["'.$entity_key.'"]) {
						if (typeof(item_selected["'.$entity_key.'"][x]) == "string") {
							$("#check_item_'.$entity_key.'_"+item_selected["'.$entity_key.'"][x]).attr("src","im/checkbox_page.png").attr("rel","1").parents("tr").addClass("fw-tr_selected");
						}
					}

				  	$(".fg-button").hover(
				  		function(){ $(this).removeClass("ui-state-default").addClass("ui-state-focus"); },
				  		function(){ $(this).removeClass("ui-state-focus").addClass("ui-state-default"); }
				  	);
	
					$("#actions_'.$entity_key.'").fg_menu({
						content: $("#'.$entity_key.'_selector_content").html(), // grab content from this page
						flyOut: true,
						showSpeed: 400
					});';
			}
		}
	} else {
		$r .= '</thead><tbody><tr><td colspan="'.count($data['header_name']['name']).'"><br/>'.fw_notify_msg('no result').'</td></tr>';
	}

	$r .= $add_row;
	$r .= '</tbody>';
	$r .= '</table>';

	if ($resizeable) {
		$script .= '
			$("#table_listing_'.$data['entity_key'].'").tableresizer({
				entity : "'.$data['entity'].'",
				entity_key : "'.$data['entity_key'].'",
				mod : "'.$_REQUEST['mod'].'",
				item_id : "'.$_REQUEST['item_id'].'",
			});
		';
	}
	
	$script = '
		<script type="text/javascript">
			var entity_update_filter = "'.msg('entity_update_filter').'";
			var entity_close_group = "'.msg('entity_close_group').'";
			'.$script.'
		</script>';
	
	if ($data['disable_dynamic_grid'] != 1) {
		$r .= '
		<div style="padding: 0 4px 4px; border-bottom: 1px solid #E3E3E3; border-left: 1px solid #E3E3E3; border-right: 1px solid #E3E3E3;">
			<div class="ui-state-active table_bar" style="border: 0">' . $pagination . $t . '</div>
		</div>';
	}
	$r .= $info.$script;
	return $r;
}

function export_clean($v) {
	if (is_array($v)) {
		foreach ($v as $k => $vx) {
			if (is_array($vx)) {
				$v[$k] = export_clean($vx);
			} else {
				$v[$k] = htmlspecialchars_decode(strip_tags($vx));
			}
		}
	} else {
		$v = htmlspecialchars_decode(strip_tags($v));
	}
	return $v;
}

/*
 * return header with link if not skip sorting
 */
function fw_add_sorting_headers($org,$val,$link){
	if ($_REQUEST['page']) $link .= '&amp;page='.$_REQUEST['page'];
	if ($_REQUEST['limit']) $link .= '&amp;limit='.$_REQUEST['limit'];

	$link = $link;
	$linka = str_replace('{sort_by}',$val['h'],$link);
	$link_ASC = str_replace('{sort_order}','ASC',$linka);
	$link_DESC = str_replace('{sort_order}','DESC',$linka);

	if ($org == 1) $h = $val['name'];
	else{
		if ($_REQUEST['sort_by'] == $val['h']) {
			if ($_REQUEST['sort_order'] == 'ASC') {
				$link1 = '<a href="'.$_SERVER['PHP_SELF'].'?'.$link_DESC.'">{h1}</a>';
				$h = str_replace('{h1}',$val['name'].'&uarr;',$link1);
				$link_return = $link_DESC;
			} else {
				$link1 = '<a href="'.$_SERVER['PHP_SELF'].'?'.$link_ASC.'">{h1}</a>';
				$h = str_replace('{h1}',$val['name'].'&darr;',$link1);
				$link_return = $link_ASC;
			}
		} else {
			$link1 = '<a href="'.$_SERVER['PHP_SELF'].'?'.$link_ASC.'">{h1}</a>';
			$h = str_replace('{h1}',$val['name'],$link1);
			$link_return = $link_ASC;
		}
	}
	return array('h' => $h);
}

function fw_add_sorting_headers_js($entity, $org, $val, $link, $replace = ''){
	if ($replace == '') {
		$replace = 'div#listing_result';
	}
	$linka = str_replace('{sort_by}', $val['h'], $link);
	$link_ASC = str_replace('{sort_order}', 'ASC', $linka);
	$link_DESC = str_replace('{sort_order}', 'DESC', $linka);

	if ($org == 1) {
		$h = $val['name'];
	} else {
		if ($_REQUEST[$entity]['sort_by'] == $val['h']) {
			if ($_REQUEST[$entity]['sort_order'] == 'ASC') {
				$link1 = '<a href="#ASC" onclick="load_page(\''.$replace.'\',\'index.php?ajax=1&'.$link_DESC.'\')">{h1}</a>';
				$h = str_replace('{h1}',$val['name'].' <span class="ui-icon ui-icon-triangle-1-n" style="float: right;"></span>',$link1);
				$h = str_replace('{h1}','<span class="ui-icon ui-icon-triangle-1-n" style="padding-right: 20px; display: inline;"></span> '.$val['name'],$link1);
				$link_return = $link_DESC;
			} else {
				$link1 = '<a href="#ASC" onclick="load_page(\''.$replace.'\',\'index.php?ajax=1&'.$link_ASC.'\')">{h1}</a>';
				$h = str_replace('{h1}',$val['name'].' <span class="ui-icon ui-icon-triangle-1-s" style="float: right;"></span>',$link1);
				$h = str_replace('{h1}','<span class="ui-icon ui-icon-triangle-1-s" style="padding-right: 20px; display: inline;"></span> '.$val['name'],$link1);
				$link_return = $link_ASC;
			}
		} else {
			$link1 = '<a href="#DESC" onclick="load_page(\''.$replace.'\',\'index.php?ajax=1&'.$link_ASC.'\')">{h1}</a>';
			$h = str_replace('{h1}',$val['name'].' <span class="ui-icon ui-icon-triangle-2-n-s" style="float: right;"></span>',$link1);
			$h = str_replace('{h1}','<span class="ui-icon ui-icon-triangle-2-n-s" style="padding-right: 20px; display: inline;"></span> '.$val['name'],$link1);
			$link_return = $link_ASC;
		}
	}
	return array('h' => $h);
}

/**
 * Enter description here...
 *
 * @param unknown_type $headers
 * @param unknown_type $fields
 * @param unknown_type $header_def
 * @param unknown_type $link
 * @return unknown
 */
function fw_headers($headers, $entity, $fields, $header_def, $link, $replace = ''){
	global $dd;
	$header['table'] = $headers['table'];
	//pass params for link $link
	if (is_array($headers['h'])) {
		foreach ($headers['h'] as $k => $v) {
			$mr = 0;
			$h1['h']='';
			if (!strstr($v, ';')) {
				if (substr($v,0,2) == 's_') {
					$hx = explode('_', $v, 2);
					$h1['h'] = $hx[1];
					$mr = 1;
				} else {
					$h1['h'] = $v;
				}

				if ($header_def[$k] != '') {
					$h1['name'] = $header_def[$k];
				} else if ($fields[$v]['head'] != '') {
					$h1['name'] = $fields[$v]['head'];
				} else {
					$h1['name'] = $h1['h'];
				}

				if ($headers['js'] == 1) {
					$check_name_link = fw_add_sorting_headers_js($entity, $mr, $h1, $link, $replace);
				} else {
					$check_name_link = fw_add_sorting_headers($mr, $h1, $link);
				}
				$header['name'][$k] = $check_name_link['h'];
				$header['all'][] = '{'.$h1['h'].'}';
			} else {
				$exp = explode(';', $v);
				foreach ($exp as $k1 => $v1) {
					if (substr($v1, 0, 2) == 's_') {
						$hx = explode('_', $v1, 2);
						$h1['h'] = $hx[1];
					} else {
						$h1['h'] = $v1;
					}

					if ($header_def[$k] != '') {
						$key_def = explode(';', $header_def[$k]);
						if ($key_def[$k1] != '') {
							$h1['name'] = $key_def[$k1];
						}
					} else if ($fields[$v1]['head'] != '') {
						$h1['name'] = $fields[$v1]['head'];
					} else {
						$h1['name'] = $h1['h'];
					}

					if ($headers['js'] == 1) {
						$check_name_link = fw_add_sorting_headers_js($entity, $mr, $h1, $link, $replace);
					} else {
						$check_name_link = fw_add_sorting_headers($mr, $h1, $link);
					}
					$header['name'][$k][$k1] = $check_name_link['h'];
					$header['all'][] = '{'.$h1['h'].'}';
				}
			}
		}
		$header['width'] = $headers['width'];
	} else if ($headers['info']) {
		foreach ($headers['info'] as $field => $info) {
			$header['width'][$field] = $info['width'];
			$v = $info['h'];
			$mr = 0;
			$h1['h']='';
			if (!strstr($v, ';')) {
				if (substr($v,0,2) == 's_') {
					$hx = explode('_', $v, 2);
					$h1['h'] = $hx[1];
					$mr = 1;
				} else {
					$h1['h'] = $v;
				}

				if ($info['header_def'] != '') {
					$h1['name'] = $info['header_def'];
				} else if ($fields[$v]['head'] != '') {
					$h1['name'] = $fields[$v]['head'];
				} else {
					$h1['name'] = '';
				}

				$check_name_link = fw_add_sorting_headers_js($entity, $mr, $h1, $link, $replace);

				$header['name'][$field] = $check_name_link['h'];
				$header['all'][$field] = '{'.$h1['h'].'}';
			} else {
				$exp = explode(';', $v);
				foreach ($exp as $k1 => $v1) {
					if (substr($v1, 0, 2) == 's_') {
						$hx = explode('_', $v1, 2);
						$h1['h'] = $hx[1];
					}else {
						$h1['h'] = $v1;
					}

					if ($info['header_def'] != '') {
						$key_def = explode(';', $info['header_def']);
						if ($key_def[$k1] != '') {
							$h1['name'] = $key_def[$k1];
						}
					} else if ($fields[$v1]['head'] != '') {
						$h1['name'] = $fields[$v1]['head'];
					} else {
						$h1['name'] = $h1['h'];
					}

					$check_name_link = fw_add_sorting_headers_js($entity, $mr, $h1, $link, $replace);

					$header['name'][$field][$k1] = $check_name_link['h'];
					$header['all'][$field] = '{'.$h1['h'].'}';
				}
			}
		}
	} else {
		$header='need header array!!';
	}
	return $header;
}

/*
 * return item list with table
 */
function fw_entity_list($basics, $clean_basics = '') {
	global $db;
	if ($clean_basics == 1) {
		$cleanVar = fw_data_cleanup('', $basics);
		$basics = $cleanVar[1];
	}

	if (count($basics['header_name']['name']) < count($basics['pattern']) || $basics['header_name']['name']['shorthand']) {
		$basics['clean_info'] = 1;
	}
	if ($basics['search_form'] != '-' && $basics['search_form'] != '0') {
		$search_form = $basics['search_form'];
	}
	return $search_form . fw_list_create($basics, $basics['pattern'], $basics['add_row'], $basics['resize_table']);
}

function fw_list_export($basics,$fields){
	global $db;
	$h = '<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<style type="text/css">
	body, td, th{font-family: Tahoma; font-size: 11px; vertical-align: top;}
	td, th{border: 1px solid #DDD; empty-cells: show;}
	a img{border: 0;}
	</style>
	</head>
	<body>
	<h3>';
	if (isset($basics['listing_header'])) $h .= $basics['listing_header'];
	else $h .= $basics['header_list'];
	$h .= '</h3>';
	$f = '</body>
	</html>';
	$function = 'fw_'.$basics['table'].'_listing';
	if (function_exists($function)) {
		$r = $function();
	} else {
		$r = '<table cellspacing="0" cellpadding="3">
		<tr><th>ID</th>';
		$sql = 'SELECT '.$basics['key'];
		foreach ($fields as $k => $v) {
			if ($v['type'] != 'H') {
				//define query
				if (($v['type'] == 'C' && $v['param2']['multi'] == 'X') || $v['type'] == 'IM' || $v['type'] == 'E' || $v['skip'] == 1) {
					1;//skip
				} else {
					$sql .= ', `'.$k.'`';
				}
				$r .= '<th>'.$v['head'].'</th>';//define header
			} else {
				unset($fields[$k]);
			}
		}
		$r .= '</tr>';
		$sql .= ' FROM `'.$basics['table'].'` WHERE 1';
		if ($basics['log_removed'] == 1) {
			$sql .= ' AND (removed_by=0 OR removed_by is NULL)';
		}
		$sql .= $basics['list_query_add'];
		if (isset($basics['listing_query'])) {
			$sql = $basics['listing_query'];
		}
		$res = $db->Execute($sql, 'fw');
		while($row=$res->FetchRow()) {
			$r .= '<tr><td>'.$row[$basics['key']].'</td>';
			$basics['id'] = $row[$basics['key']];
			$fields = fwGetValues($fields,$basics,$row);//update values
			foreach ($fields as $k => $v) {
				$v['value_only'] = 1;
				#check custom function for skip fields
				$f = PREFIX.$_REQUEST['mod'].'_'.$_REQUEST['view'].'_'.$k;
				if (function_exists($f)){
					$vx = $f($v,'show',$basics['id']);
					$r .= '<td>'.$vx.'</td>';
				} else {
					$r .= '<td><span class="edit_me" rel="'.$basics['table'].'|'.$k.'|'.$basics['id'].'">'.fw_form_item($k,$v,$basics).'</span></td>';
				}
			}
			$r .= '</tr>';
		}
		$r .= '</table>';
	}
	if ($_REQUEST['xls'] == 1) {
		$ws_name = str_replace(PREFIX, '', $basics['table']).'_listing';
		$table = array(
			$ws_name => array(
				'table' => $r,
				'header' => $basics['header_list'],
				'column_width' => $basics['xls_columns']
			)
		);
		fw_export_excel($table,$ws_name);
		return 1;
	} else {
		$r .= '<br/><a href="'.$_SERVER['PHP_SELF'].$_SERVER['REQUEST_URI'].'&xls=1">'.INF_XLS_EXPORT.'</a>';
		return $h.$r.$f;
	}
}

/*
 * return query [limit 0,...]
 */
function fw_list_sort_limit($headers, $sort, $entity = ''){
	$qry = '';
	$set_page = 0;
//	$sort['order'] = $_REQUEST[$entity]['sort_order'];
	if ($_REQUEST[$entity]['sort_order']) {
		$sort['order'] = $_REQUEST[$entity]['sort_order'];
	}
	if ($sort['order'] != 'DESC') {
		$sort['order'] = 'ASC';
	}
	$order_by = $sort['by'];
	if ($_REQUEST[$entity]['sort_by'] != '') {
		$order_by = $_REQUEST[$entity]['sort_by'];
	}

	$set_page = $sort['page'];
	if ($_REQUEST[$entity]['page']) {
		$set_page = $_REQUEST[$entity]['page'];
	}

	#check order by
	if ($headers['info']) {
		foreach ($headers['info'] as $k => $info) {
			$v = $info['h'];
			if (strstr($v,';')) {
				$exp = explode(';', $v);
				foreach ($exp as $i => $o) {
					$allheaders[] = $o;
				}
			} else {
				$allheaders[] = $v;
			}
		}
		if (!in_array($order_by, $allheaders)) {
			$order_by = $sort['by'];
		}
	}

	#need to set for show correct page number for next function!
	$_REQUEST[$entity]['page'] = $set_page;
	$_REQUEST[$entity]['sort_by'] = $order_by;
	$_REQUEST[$entity]['sort_order'] = $sort['order'];
	#add query add for set sort by and sort order
	$qry = ' ORDER BY '.$order_by.' '.$sort['order'];

	if ($sort['permanent_sort']) {
		$qry .= ', '.$sort['permanent_sort'];
	}

	if ($_REQUEST['export'] != 1) {
		#prepare qry for limit
		$set_limit = '';
		if ($_REQUEST[$entity]['limit'] > 0) {
			$set_limit = $_REQUEST[$entity]['limit'];
		} else if ($sort['limit'] != '') {
			#use default
			$set_limit = $sort['limit'];
		}
	
		if ($set_limit) {
			$qry .= ' LIMIT '.(int)($set_page*$set_limit).', '.$set_limit;
		}
	}
	return $qry;
}

?>